package com.example.monkey.textview_show;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.lang.reflect.Field;


public class MainActivity extends ActionBarActivity {

    public int getResourceID(String name) {
        try{
            //根据资源的ID的变量名获得Field的的对象,使用反射机制来实现
            Field field = R.drawable.class.getField(name);
            //取得并返回资源的ID的字段(静态变量)的值，使用反射机制
            return Integer.parseInt(field.get(null).toString());
        } catch(Exception e) {

        }
        return 0;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView) this.findViewById(R.id.textview);
        textView.setTextColor(Color.BLACK);
        textView.setBackgroundColor(Color.WHITE);
        textView.setTextSize(20);
        String html = "图像1<img src='image1'/>图像2<img src='image2'/>图像3<img src='image3'/><p>";
        html += "图像4<a href='http://www.baidu.com'><img src='image4'></a>图像5<img src='image5'/>";

        CharSequence charSequence = Html.fromHtml(html,new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                //获得系统资源的信息，比如图片信息
                Drawable drawable = getResources().getDrawable(getResourceID(source));
                // 第3个图片按照50%的比例进行压缩
                if(source.equals("imag3")) {
                    drawable.setBounds(0,0,drawable.getIntrinsicWidth()/2, drawable.getIntrinsicHeight()/2);
                } else {
                    drawable.setBounds(0,0,drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                }
                return drawable;
            }
        },null);
        textView.setText(charSequence);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
